package com.gallery.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gallery.exceptions.DataBaseException;
import com.gallery.exceptions.LoginFailedException;
import com.gallery.exceptions.UpLoadFailedException;
import com.gallery.result.Result;
import com.gallery.service.IImagesService;
import com.gallery.service.IUserService;
import com.gallery.utils.AliOssUtil;
import dto.UserDTO;
import dto.UserLoginDTO;
import entity.Images;
import entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import vo.UserLoginVO;
import vo.UserVO;

import java.io.IOException;
import java.security.PrivilegedAction;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * @param
 * @return
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Slf4j
public class UserController {
    private final  IUserService userService;

    private final AliOssUtil aliOssUtil;

    private final IImagesService imagesService;

    private final RedisTemplate redisTemplate;
    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<UserLoginVO>login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("获取到登录信息:{}",userLoginDTO);
       UserLoginVO userLoginVO= userService.login(userLoginDTO);
        return Result.success(userLoginVO);
    }

    /**
     * 用户注册
     * @param userDTO
     * @return
     */
    @PostMapping("/register")
    public Result save(@RequestBody UserDTO userDTO){
        log.info("获取到员工注册:{}",userDTO);
        User user=new User();
        user.setNums(0L);
        BeanUtils.copyProperties(userDTO,user);
        try {
            userService.save(user);
        } catch (Exception e) {
            throw new DataBaseException("已有用户注册！请更换用户名！");
        }
        return Result.success();
    }


    /**
     * 上传照片
     * @param file
     * @param clazz
     * @param name
     * @param status
     * @return
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam List<MultipartFile> file,@RequestParam(required = false) String clazz,
                         @RequestParam String name,@RequestParam(required = false)String status){
        redisTemplate.delete("user_"+ StpUtil.getLoginIdAsLong());
        String filePath;
        String finalFilePath="";
//        for (MultipartFile file1:file){
//            try {
//                //原始文件名
////                filePath=file1.getOriginalFilename();
//                String originalFilename = file1.getOriginalFilename();
//                String extention = originalFilename.substring(originalFilename.lastIndexOf("."));
//                String objectname = UUID.randomUUID().toString() + extention;
//                filePath = aliOssUtil.upload(file1.getBytes(), objectname);
//                finalFilePath+=filePath+",";
//            }catch (Exception e){
//                throw new UpLoadFailedException("文件上传失败！");
//            }
//        }

        //图片存入数据库
        Images  images=new Images();
        images.setAllHot(0L);
        images.setClazz(clazz);
        images.setDayHot(0L);
        images.setUserId(StpUtil.getLoginIdAsLong());
        images.setName(name);
        images.setUploadTime(LocalDateTime.now());
        images.setUrl(finalFilePath);
        if (StrUtil.isBlank(status)){
            images.setStatus("1");
        }else {
            images.setStatus(status);
        }
        //更新图片数量
        imagesService.save(images);
        User user = userService.getById(StpUtil.getLoginIdAsLong());
        Long nums = user.getNums()+1;
        user.setNums(nums);
        userService.updateById(user);

        String[] split = finalFilePath.split(",");
        for (int i=0;i<split.length;i++){
            System.out.println(split[i]);
        }
        return Result.success();

    }

    /**
     * 修改密码
     * @param user
     * @param newpassword
     */
    @PostMapping("/password/{newpassword}")
    public Result password(User user, @PathVariable String newpassword){
        log.info("获取到新密码：{}",newpassword);
        User one = userService.lambdaQuery()
                .eq(User::getId, StpUtil.getLoginIdAsLong())
                .eq(User::getPassword, user.getPassword())
                .one();
        if(ObjectUtil.isEmpty(one)){
            throw new LoginFailedException("密码错误!");
        }
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<User>()
                .set(User::getPassword, newpassword)
                .eq(User::getId, StpUtil.getLoginIdAsLong());
        userService.update(null,wrapper);
        return Result.success();
    }

    /**
     * 查询用户
     * @param userDTO
     * @return
     */
    @GetMapping("/use")
    public Result<List<User>> use(UserDTO userDTO){
        String username = userDTO.getUsername();
        String sex = userDTO.getSex();
        List<User> list = userService.lambdaQuery()
                .like(username != null, User::getUsername, username)
                .eq(sex != null, User::getSex, sex)
                .list();

        return Result.success(list);
    }

    /**
     * 查询用户详细
     * @return
     */
    @GetMapping("/myself")
    public Result<UserVO> myself(){
        UserVO userVO = userService.myself();
        return Result.success(userVO);
    }
}
